﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Diagnostics;

namespace OpenDynDnsChanger.Service.Updates.Provider
{
    internal class SP_NoIP : IDnsUpdater
    {
        WebRequest _request;

        public void Update(string ip, string userName, string passwort)
        {
            try
            {
                string requestUrl = "http://dynupdate.no-ip.com/nic/update?hostname=sspssp.zapto.org&myip=" + ip.ToString();

                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

                request.Credentials = new NetworkCredential(userName, passwort);

                WebResponse response = request.GetResponse();

                StreamReader reader = new StreamReader(response.GetResponseStream());

                string responseBody = reader.ReadToEnd();

                reader.Close();
                reader.Dispose();

                UpdateCallbackResult result = new UpdateCallbackResult();

                if(responseBody.ToLower().StartsWith("nochg"))
                {
                    result.ResultFlag = Enums.UpdateResult.NotChanged;
                }
                else if(responseBody.ToLower().StartsWith("good"))
                {
                    result.ResultFlag = Enums.UpdateResult.Succsess;
                }



                result.RawResult = responseBody;

                if (Callback != null)
                    Callback.Invoke(result);

            }
            catch (Exception ex)
            {
                EventLog.WriteEntry(Consts.ServiceName, ex.Message + Environment.NewLine + ex.StackTrace, EventLogEntryType.Error);
            }

            Console.ReadLine();
        }

        public DnsUpdateCallback Callback
        {
            get;
            set;
        }


    }
}
